package com.imooc.sm.global;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //过滤一些必须登录才有的页面
        String path = request.getServletPath();
        System.out.println("这个请求是...."+path);
        if (path.toLowerCase().indexOf("login")!= -1){
            filterChain.doFilter(request,response);
        }else{
            HttpSession session = request.getSession();
            Object object = session.getAttribute("USER");
            if (object != null){
                filterChain.doFilter(request,response);
            }else{
                response.getWriter().print("<script type=\"text/javascript\">parent.location.href=\"../logout.do\"</script>");
                response.sendRedirect(request.getContextPath()+"/toLogin.do");
            }
        }

    }

    @Override
    public void destroy() {

    }
}
